package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.pojo.Orders;
import com.itheima.reggie.service.OrdersService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

/**
 * 订单管理
 */
@RestController
@RequestMapping("order")
@Slf4j
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    /**
     * 后台查询订单
     * @param number 查询条件
     * @param beginTime 起始时间
     * @param endTime 结束时间
     * @return 查询结果
     */
    @GetMapping("page")
    @SneakyThrows
    /* @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") */
    public R<Page<Orders>> page(int page, int pageSize, Long number,  String beginTime, String endTime){
        log.info("查询订单: 条件:{} 起始时间:{} 结束时间:{}", number, beginTime, endTime);

        Page<Orders> ordersPage = new Page<>(page, pageSize);
        ordersPage = ordersService.ordersPage(ordersPage, number, beginTime, endTime);
        return R.success(ordersPage);
    }

    /**
     * 用户下单
     * @param orders 订单信息
     * @return 返回结果
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        Long userId = BaseContext.getCurrentId();
        log.info("用户 {} 下单{}", userId, orders);

        ordersService.sbumit(orders);

        return R.success("下单成功");
    }

    /**
     * 用户订单分页查询
     * @param page, pageSize
     * @return 查询结果
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(int page, int pageSize){
        Long userId = BaseContext.getCurrentId();
        log.info("用户:{} 订单分页查询", userId);

        Page<OrdersDto> ordersPage = new Page<>( page, pageSize);
        ordersPage = ordersService.userPage( ordersPage, userId);

        return R.success(ordersPage);
    }

    /**
     * 修改订单状态
     * @param orders 订单信息
     */
    @PutMapping()
    public R<String> updateStatus(@RequestBody Orders orders){
        log.info("修改订单状态{}", orders);
        ordersService.updateById(orders);
        return R.success("完成");
    }
}
